<template>
<div>
  <div class="table-seatch-flex">
    <div class="table-search">
      <div class="search-left">
        <div class="search-item">
          <span class="search-label">合同名称</span>
          <div class="search-input">
            <a-input v-model:value="searchObj.contractName" :bordered="false" placeholder="请输入合同名称"></a-input>
          </div>
        </div>
        <CustomInput :isClear="isClear" :custom="item" @changeVal="onChangeVal" @closeId="closeInput" v-for="item in searchArr" :key="item.id"/>
        <div class="search-btn">
          <div class="search-icon">
            <a-cascader
                v-model:value="value"
                placeholder="Please select"
                :options="selectOption"
                :fieldNames="{
                  label: 'name',
                  value: 'key'
                }"
                @change="onChange"
            >
              <PlusOutlined/>
            </a-cascader>
          </div>
          <a-button class="search-btn2" @click="resetCustom">
            <template #icon>
              <RedoOutlined/>
            </template>
            重置
          </a-button>
          <a-button class="search-btn1" @click="searchTable">查询</a-button>
<!--          <a-button type="text">更多筛选条件</a-button>-->
        </div>
      </div>
    </div>
  </div>

  <div class="table-box">
    <div class="table-btn-flex">
      <div>
        <a-radio-group v-model:value="activeKey" style="margin: 8px" @change="changeRadio">
          <a-radio-button value="1">备忘录</a-radio-button>
          <a-radio-button value="2">主合同</a-radio-button>
        </a-radio-group>
        <a-button type="text" @click="addColumn">
          <template #icon>
            <FilterOutlined />
          </template>
          自定义列</a-button>
      </div>

      <div>
        <a-button class="search-btn1" @click="goAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          新增</a-button>
        <a-button class="border-btn" @click="exportTable">
          <template #icon>
            <DownloadOutlined />
          </template>
          导出</a-button>
      </div>
    </div>
     <div class="table-div">
       <ReturnTable ref="memorandumForm" v-if="activeKey === '1'" :customData="customData"
                    :changeValObj="searchObj"
                    :isSearch = "isSearch"
                    @exportData="onExportData"
                    :customUpdate="customUpdate"/>
       <MasterContract ref="masterForm" v-if="activeKey === '2'" @exportData="onExportData"  :changeValObj="searchObj"
                       :isSearch = "isSearch"
                       :customData="customData" :customUpdate="customUpdate"/>
     </div>
  </div>
  <CustomColumnModel ref="columnForm"
                     @saveColumn="onSaveColumn"
                     :customData="customData"
                     :columSaveData="columSaveData"
                     :module="activeModule"/>
  <AddContract ref="ContractModel" @saveMemForm="onSaveMemForm"/>
  <AddMainContract ref="MainModel" @saveForm="onSaveForm"/>
</div>
</template>

<script setup>
import {ref, getCurrentInstance,watch, onMounted} from 'vue';
const { proxy  } = getCurrentInstance()
import { DownloadOutlined, PlusOutlined, RedoOutlined, FilterOutlined } from '@ant-design/icons-vue';
import MasterContract from "@/pages/ResourceContract/components/ArrangementTable/MasterContract.vue";
import ReturnTable from "@/pages/ResourceContract/components/ArrangementTable/ReturnTable.vue";
import AddContract from './AddContract.vue'
import CustomColumnModel from './CustomColumnModel.vue'
import CustomInput from '@/components/CustomInput/CustomInput.vue'
import AddMainContract from './AddMainContract.vue'
import {message} from "ant-design-vue";
const value = ref(['b'])
const selectOption = ref([])
const searchArr = ref([])
const activeModule = ref('con_resource_memorandum')
const customUpdate = ref('')
const customData = ref([])
const selectOptionAll = ref([])
const isClear = ref(false)
const searchObj = ref({
  contractName: ''
})
watch( () => customData, (newVal) => {
  console.log('数据更新了', newVal)
  customData.value = newVal.value
},
    {
      deep: true
    }
)
// 选择展示搜索项
const onChange = (value) => {
  console.log('选择的是', value[0])
  selectOptionAll.value.map((item) => {
    if (value[0] === item.key) {
      postSaveQuery(item.key)
      console.log('新增的是')
      selectOption.value = selectOption.value.filter(items => items.key !== item.key)
      console.log('筛选的', selectOption.value)
    }
  })
}
// 关闭展示搜索项
const closeInput = (val) => {
  console.log('删除的是', val.id)
  deleteQuery(val.id)
  selectOption.value.push(val)
  // searchArr.value = searchArr.value.filter(item => item.id !== val.id)
}
// 重置展示搜索项
const resetCustom = () => {
  searchObj.value.contractName = ''
  changeObjArr.value = []
  let searchKey = Object.keys(searchObj.value)
  searchKey.map(key => {
    searchArr.value.map(item => {
      if (key === 'queryParams') {
       let queryKey = Object.keys(searchObj.value.queryParams)
        queryKey.map(childKey => {
          searchObj.value[key][childKey] = ''
        })
      } else  {
        if (item.key === key) {
          searchObj.value[key] = ''
        }
      }

    })
  })
  changeObj.value = searchObj.value
  changeObjArr.value.push(searchObj.value)
  isClear.value = true
  isSearch.value = false
}
// 拿到框中的值
const changeObj = ref({})
const onChangeVal = (val) => {
  isClear.value = false
  changeObj.value = val
  isSearch.value = false
  console.log('传了', val)
  console.log('拿到的值', changeObj.value)
}
const activeKey = ref('1')
const ContractModel = ref()
const MainModel = ref()
const goAdd = () => {
  if (activeKey.value === '1') {
    ContractModel.value.showModal()
  } else {
    MainModel.value.showModal()
  }
}
const columnForm = ref()
const masterForm = ref() // 主合同
const memorandumForm = ref() //备忘录
const columSaveData = ref([])
const addColumn = () => {
  customUpdate.value = ''
  let list = []
  let newList = []
  if (activeKey.value === '1') {
     list = memorandumForm.value.getColumCustom()
     newList = JSON.parse(JSON.stringify(list))
  } else {
     list = masterForm.value.getColumCustom()
     newList = JSON.parse(JSON.stringify(list))
  }
  console.log('保存的列',newList)
  if (newList.length > 0) {
    newList.map(item => {
      if (item.key !== 'tags') {
        columSaveData.value.push(item.key)
      }
    })
  }
  columnForm.value.showModal()
  console.log('获取到保存的值没', columSaveData)
  getPageList()
}
const onSaveColumn = (item) => {
console.log('传回来的item', item)
  customUpdate.value = item
  columSaveData.value = []
}
const changeRadio = (e) => {
  console.log('点击的时', e)
  activeKey.value = e.target.value
  activeModule.value = e.target.value === '1'? 'con_resource_memorandum' : 'con_resource_main'
  getPageList()
  getQuery()
}
/**
 * 获取显示列
 * */
const getPageList = () => {
  let customObj = {
    module: activeModule.value
  }
  /**
   * 列表展示所有列
   * */
  proxy.$api.getTableColumnCustom(customObj).then(res => {
    console.log('成功了没列', res)
    customData.value = res.resultObject
  })
}
/**
 * 获取筛选列
 * */
const getQuery = () => {
  let customObj = {
    module: activeModule.value
  }
  /**
   * 列表帅选列
   * */
  proxy.$api.getQueryItem(customObj).then(res => {
    console.log('筛选列', res)
    selectOptionAll.value = res.resultObject
    selectOption.value = JSON.parse(JSON.stringify(selectOptionAll.value))
    selectOption.value = selectOption.value.filter(items => items.key !== 'contractName' )
    getQueryItemList()
  })
}
/**
 * 保存增加的筛选列
 * */
const postSaveQuery = (key) => {
  let saveObj = {
    module: activeModule.value,
    columnKey: key
  }
  proxy.$api.postQueryItem(saveObj).then(res => {
    console.log('保存了增加的筛选列', res)
    getQueryItemList()
  })
}
/**
 * 删除增加的筛选配置
 * */
const deleteQuery = (id) => {
   proxy.$api.deleteQueryItem({id: id}).then(res => {
     console.log('删除了筛选列', res)
     getQueryItemList()
   })
}
/**
 * 获取已经保存的筛选列
 * */
const getQueryItemList = () => {
  let customObj = {
    module: activeModule.value
  }
  proxy.$api.getSaveQueryItem(customObj).then(res => {
    let userData = res.resultObject
    searchArr.value = []
    if (userData.length > 0) {
      selectOptionAll.value.map((item) => {
        userData.map(childItem => {
          if (item.key === childItem.columnKey) {
            let newItem = {
              id: '',
              key: '',
              name: '',
              userId: '',
              module: '',
              options: [],
              valueFormat: '',
              type: ''
            }
            Object.assign(newItem, {
              id: childItem.id.toString(),
              key: childItem.columnKey,
              name: item.name,
              userId: newItem.userId,
              module:  newItem.module,
              options: item.options,
              valueFormat: item.valueFormat,
              type: item.type
            })
            selectOption.value = selectOption.value.filter(items => items.key !== childItem.columnKey)
            searchArr.value.push(newItem)
            const hash = {}
            searchArr.value =  searchArr.value.reduce((item,next) => {
              hash[next.key]? '' : hash[next.key] = true && item.push(next)
              return item
            }, [])
            console.log('筛选的AAA', searchArr.value)
          }
        })
      })
    } else {
      searchArr.value = []
    }

  })
}
const isSearch = ref(false)
const changeObjArr = ref([])
const changeQuery = ref([])
watch(() => changeObj.value, newVal => {
  isSearch.value = false
  if (newVal.queryParams) {
    changeQuery.value.push(newVal.queryParams)
    let queryObj = changeQuery.value.reduce((acc, value) => {
      return {...acc, ...value}
    })
    newVal.queryParams = queryObj
  }
  changeObjArr.value.push(newVal)
})
const searchTable = () => {
  changeObjArr.value.map(item => {
    searchObj.value = Object.assign(searchObj.value, item)
  })
  isSearch.value = true
  console.log('点击查询了', searchObj.value)
}

/**
 * 新增了主合同表格数据
 * */
const onSaveForm = (val) => {
  if (val) {
    masterForm.value.getUserColum()
  }
}
/**
 * 新增了备忘录表格数据
 **/
const onSaveMemForm =  (val) => {
  if (val) {
    memorandumForm.value.getUserColum()
  }
}
/**
 * 导出
 * */
const exportList = ref({
  ids: [],
  contractNumber: '',
  contractName: ''
})
const onExportData = (val) => {
  console.log('导出的数据', val)
  if (val && val.length > 0) {
    val.map(item => {
      exportList.value.ids.push(item.id)
      exportList.value.contractNumber = item.contractNumber
      exportList.value.contractName = item.contractName
    })
  }
}
const exportTable =() => {
  if (activeKey.value === '1') {
    proxy.$api.exportMemorandum(exportList.value).then(res => {
      if (res.resultCode === 0) {
        message.success('导出成功，请到导出记录中下载')
        memorandumForm.value.getSelect()
      }
    })
  } else {
    proxy.$api.exportResoureMain(exportList.value).then(res => {
      if (res.resultCode === 0) {
        message.success('导出成功，请到导出记录中下载')
        masterForm.value.getSelect()
      }
    })
  }
}
onMounted(() => {
  getPageList()
  getQuery()
  console.log('customData.valu', customData.value)
})
</script>

<style lang="scss" scoped>
.table-seatch-flex {
  border-bottom: 1px solid #DCDEE0;
  background: #ffffff;
  padding: 24px 0 0 0;
  //margin-top: 24px;
  .table-search {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .search-left {
      display: flex;
      width: 100%;
      flex-wrap: wrap;
      .search-item {
        margin-left: 10px;
        border: 1px solid  #DCDEE0;
        height: 34px;
        line-height: 32px;
        display: flex;
        width: 330px;
        margin-bottom: 24px;
        position: relative;
        font-size: 14px;
        .search-label {
          display: block;
          //width: 80px;
          line-height: 32px;
          color: #2C3749;
          padding: 0 12px;
          text-align: left;

        }
        //span {
        //  display: block;
        //  width: 80px;
        //  line-height: 32px;
        //  color: #2C3749;
        //}
        .search-input {
          width: 247px;
          text-align: left;
        }
        .close-btn {
          position: absolute;
          top: -17px;
          right: -4px;
        }
      }
      .search-btn {
        margin-left:20px;
        display: flex;
        margin-bottom: 12px;
        .search-btn1 {
          background: #f5001d;
          border-radius: 2px;
          color: #fff;
          padding: 0 20px;
        }
      }
    }
    .search-right {
      display: flex;
      margin-top: 15px;
      .search-input {
         text-align: left;
      }
    }
  }
}

.table-box {
  background: #ffffff;
  padding: 20px;
  margin-bottom: 10px;
}
.table-btn-flex {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .ant-radio-button-wrapper-checked {
    background: #0062AD;
    color: #ffffff;
  }
}
.table-div {
  margin-top: 10px;
}
</style>
